﻿using System;
using System.Text.RegularExpressions;
using EPiServer.Framework;
using EPiServer.Web;
using TemplateFoundation.Configuration;

namespace TemplateFoundation.EventHandlers
{
    /// <summary>
    /// Converts URLs to lower-case and removes extra white spaces
    /// </summary>
    [InitializableModule]
    [ModuleDependency(typeof(PageTypeBuilder.Initializer))]
    public class UrlTouchUp : IInitializableModule
    {
        private bool _creatingPageEventAttached;

        static void CreatedUrlSegment(object sender, UrlSegmentEventArgs e)
        {
            if (e.IsModified && !string.IsNullOrEmpty(e.PageData.URLSegment))
            {
                // Remove segment for pages with the char '1' on the end
                if (e.PageData.URLSegment.EndsWith("1", StringComparison.OrdinalIgnoreCase))
                {
                    e.PageData.URLSegment = string.Empty;
                }
                else
                {
                    // Remove excess '-' characters and convert to lower case only
                    e.PageData.URLSegment = Regex.Replace(e.PageData.URLSegment, "-{2,}", "-", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline).ToLower();
                }
            }
        }

        #region IInitializableModule Members

        /// <summary>
        /// Initializes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Initialize(EPiServer.Framework.Initialization.InitializationEngine context)
        {
            if (!_creatingPageEventAttached)
            {
                UrlSegment.CreatedUrlSegment += CreatedUrlSegment;
            }

            _creatingPageEventAttached = true;
        }

        /// <summary>
        /// Not implemented
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        public void Preload(string[] parameters) { throw new NotImplementedException(); }

        /// <summary>
        /// Not implemented
        /// </summary>
        /// <param name="context">The context.</param>
        public void Uninitialize(EPiServer.Framework.Initialization.InitializationEngine context) { throw new NotImplementedException(); }

        #endregion
    }
}
